package com.song.demo06springbootdata.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JdbcController {

    // spring-jdbc默认注入了xxxTemplate，template可以直接来进行操作
    @Autowired
    JdbcTemplate jdbcTemplate;

    // 查询数据库的所有信息  http://localhost:8888/userList
    // 没有实体类，数据库中的东西怎么获取？ Map
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql = "select * from user";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }

    //http://localhost:8888/addList
    @GetMapping("/addList")
    public String addList(){
        String sql = "INSERT INTO `sdmdb`.`user` (`name`, `age`) VALUES ( '王五', 12);\n";
        jdbcTemplate.update(sql);
        return "update-add-ok";
    }

    //http://localhost:8888/updateUser/2
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql = "update user set name = ?,age = ? where id = "+id;
        // 封装
        Object[] objects = new Object[2];
        objects[0] = "哥哥";
        objects[1] = "44";
        jdbcTemplate.update(sql,objects);
        return "update-update-ok";
    }

    //http://localhost:8888/deleteUser/2
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql = "delete from user  where id = "+id;
        jdbcTemplate.update(sql);
        return "update-delete-ok";
    }

}
